package com.lzh.main.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lzh.main.mapper.ChatMessageMapper;
import com.lzh.main.pojo.dto.Result;
import com.lzh.main.pojo.entity.ChatMessage;
import com.lzh.main.service.ChatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class ChatServiceImpl implements ChatService {
    @Autowired
    private ChatMessageMapper chatMessageMapper;

    @Override
    public Result sendMessage(Integer senderId, Integer receiverId, String content) {
        ChatMessage chatMessage = new ChatMessage();
        chatMessage.setSenderId(senderId);
        chatMessage.setReceiverId(receiverId);
        chatMessage.setContent(content);
        chatMessage.setIsRead(false);
        chatMessage.setCreateTime(new Date());
        chatMessageMapper.insert(chatMessage);
        return Result.success(chatMessage);
    }

    @Override
    public Result getChatHistory(Integer userId, Integer friendId) {
        QueryWrapper<ChatMessage> query = new QueryWrapper<>();
        query.and(q -> q.eq("sender_id", userId).eq("receiver_id", friendId))
                .or(q -> q.eq("sender_id", friendId).eq("receiver_id", userId))
                .orderByAsc("create_time");

        List<ChatMessage> messages = chatMessageMapper.selectList(query);
        return Result.success(messages);
    }

    @Override
    public Result getUnreadMessages(Integer userId) {
        QueryWrapper<ChatMessage> query = new QueryWrapper<>();
        query.eq("receiver_id", userId)
                .eq("is_read", false)
                .orderByAsc("create_time");

        List<ChatMessage> messages = chatMessageMapper.selectList(query);
        return Result.success(messages);
    }
}
